package org.datascooter.db.mssql;

import java.sql.SQLException;

import javax.sql.ConnectionPoolDataSource;

import net.sourceforge.jtds.jdbcx.JtdsDataSource;

import org.datascooter.impl.ContextConnector;
import org.datascooter.inface.IDataSource;

public class MssqlConnector extends ContextConnector {

	private JtdsDataSource jtdsDataSource;

	public MssqlConnector() {
	}

	public MssqlConnector(IDataSource source) throws SQLException {
		super(source);
	}

	@Override
	public ConnectionPoolDataSource createPooledDataSource() throws SQLException {
		if (jtdsDataSource == null) {
			jtdsDataSource = new JtdsDataSource();
			String addrPortBase = dataSource.getURL().substring(dataSource.getURL().indexOf("//") + 2);
			String addr = addrPortBase.substring(0, addrPortBase.indexOf(":"));
			String port = addrPortBase.substring(addrPortBase.indexOf(":") + 1, addrPortBase.indexOf("/"));
			String dbName = addrPortBase.substring(addrPortBase.indexOf("/") + 1, addrPortBase.length());
			jtdsDataSource.setServerName(addr);
			jtdsDataSource.setPortNumber(Integer.valueOf(port));
			jtdsDataSource.setDatabaseName(dbName);
			jtdsDataSource.setUser(dataSource.getUser());
			jtdsDataSource.setPassword(dataSource.getPassword());
		}
		return jtdsDataSource;
	}

	@Override
	public String getContextId() {
		return "mssql";
	}
}
